package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/*
* 有点开心
* */
@Slf4j
public class Plugin_ECARD_P026 implements ChannelService {
    private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int ALPHABET_SIZE = ALPHABET.length();
    private static final Random RANDOM = new Random();

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            long timestamp = System.currentTimeMillis() / 1000;
            String randomString = generateRandomString(30);

            HashMap<String, String> requestParams = new HashMap<>();
            requestParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));
            requestParams.put("product_id",String.valueOf(data.get("SUPProductId")));
            requestParams.put("recharge_number",String.valueOf(data.get("AccountVal")));
            requestParams.put("appid",apiConfig.getString("AppId"));
            requestParams.put("timestamp",String.valueOf(timestamp));
            requestParams.put("oncestr",randomString);
            requestParams.put("notify_url",apiConfig.getString("NotifyUrl"));

            String apiKey = apiConfig.getString("apiKey");
            String sign = generateSignature(requestParams, apiKey);
            requestParams.put("sign",sign);
            String submitUrl = apiConfig.getString("SubmitUrl");

            String res = HttpTool.sendPost(submitUrl, requestParams);
            JSONObject parseObject = JSONObject.parseObject(res);
            String rc = parseObject.getString("rc");
            if (rc.equals("1")){
                JSONObject resData = parseObject.getObject("data",JSONObject.class);
                String state = resData.getString("state");
                if (state.equals("1")) {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                if (state.equals("2")) {
                    return ChannelResult.success("充值成功");
                }
                return ChannelResult.FAILED("充值失败");
            }
            String error = parseObject.getString("error");
            return ChannelResult.error(error);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("有点开心提交订单接口错误：",e);
            return  ChannelResult.error("有点开心提交订单接口错误");
        }

    }


    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            long timestamp = System.currentTimeMillis() / 1000;
            String randomString = generateRandomString(30);
            HashMap<String, String> queryParams = new HashMap<>();
            queryParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));
            queryParams.put("appid",apiConfig.getString("AppId"));
            queryParams.put("timestamp",String.valueOf(timestamp));
            queryParams.put("oncestr",randomString);

            String apiKey = apiConfig.getString("apiKey");
            String sign = generateSignature(queryParams, apiKey);
            queryParams.put("sign",sign);
            String queryUrl = apiConfig.getString("QueryUrl");

            String res = HttpTool.sendPost(queryUrl, queryParams);
            JSONObject parseObject = JSONObject.parseObject(res);
            String rc = parseObject.getString("rc");
            if (rc.equals("1")) {
                JSONObject resData = parseObject.getObject("data", JSONObject.class);
                String state = resData.getString("state");
                if (state.equals("1")) {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                if (state.equals("2")) {
                    return ChannelResult.success("充值成功");
                }
                return ChannelResult.FAILED("充值失败");
            }
            String error = parseObject.getString("error");
            return ChannelResult.error(error);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("有点开心查询订单接口错误：",e);
            return  ChannelResult.error("有点开心查询订单接口错误");
        }
    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    public static String generateSignature(Map<String, String> params, String key) throws Exception {
        // 第一步：将请求参数根据键按照字典序排序，并按照 "key1=value1&key2=value2..." 的格式拼成一个字符串
        StringBuilder sb = new StringBuilder();
        Map<String, String> sortedParams = new HashMap<>(params);
        String[] keys = sortedParams.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        for (String paramKey : keys) {
            sb.append(paramKey).append("=").append(URLEncoder.encode(sortedParams.get(paramKey), "UTF-8")).append("&");
        }
        String A = sb.toString();
        A = A.length() > 0 ? A.substring(0, A.length() - 1) : "";

        // 第二步：将 key 拼接在第一步中排序后的字符串后面得到待加密字符串
        String signTemp = A + "&key=" + key;

        // 第三步：使用 md5 算法加密待加密字符串
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] signBytes = md5.digest(signTemp.getBytes("UTF-8"));
        StringBuilder signBuilder = new StringBuilder();
        for (byte b : signBytes) {
            signBuilder.append(String.format("%02x", b));
        }
        return signBuilder.toString();
    }
    public static String generateRandomString(int length) {
        if (length < 1) {
            throw new IllegalArgumentException("Length must be at least 1");
        }
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = RANDOM.nextInt(ALPHABET_SIZE);
            sb.append(ALPHABET.charAt(randomIndex));
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        // 测试
        HashMap<String, String> params = new HashMap<>();
        params.put("appid", "dianliang");
        params.put("ch", "dianliang");
        params.put("oncestr", "1685228421357149");
        params.put("orderId", "23052807000991000030");
        params.put("phone", "13366231560");
        params.put("timestamp", "1685228421");
        String secretKey = "7Lh4PeUP8tBwvtKgfZNU";//"7Lh4PeUP8tBwvtKgfZNU";
        String signature = generateSignature(params, secretKey);
        System.out.println("Signature: " + signature);  // 输出：Signature: 15e48f737e8f4119786502fa951f53c5
    }

}
